package com.zhang.yygh.order.controller;

import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.zhang.yygh.common.result.R;
import com.zhang.yygh.order.service.PaymentService;
import com.zhang.yygh.order.service.WeixinService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {
    @Autowired
    private WeixinService weixinPayService;

    @Autowired
    private PaymentService paymentService;

     // 下单 生成二维码
    @GetMapping("/createNative/{orderId}")
    public R createNative(
            @ApiParam(name = "orderId", value = "订单id", required = true)
            @PathVariable("orderId") Long orderId) {
        Map<String,Object> map = weixinPayService.createNative(orderId);
        return R.ok().data(map);
    }

    //查询订单状态：1.支付失败 2.支付中。。。 3.支付成功
    @GetMapping(value = "/queryPayStatus/{orderId}")
    public R queryPayStatus(@PathVariable Long orderId){
        Map<String,String> map=weixinPayService.queryPayStatus(orderId);
        if (map==null){
            return R.error().message("支付失败");
        }
        if (map.get("trade_state").equals("SUCCESS")){
            //更新订单的状态
            //更新支付记录的支付状态和其他字段
            String out_trade_no = map.get("out_trade_no");
            paymentService.paySuccess(out_trade_no, PaymentTypeEnum.WEIXIN.getStatus(), map);

            return R.ok().message("支付成功");
        }
        return R.ok().message("支付中");
    }
}
